<!--
 * @Descripttion: 盘点作业表
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-05-15 18:24:54
 * @LastEditors: GW
 * @LastEditTime: 2022-06-11 11:50:34
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="searchList('list')" v-if="showModel=='order'">
                                <a-icon class="btns-icon" type="unordered-list" />
                                <div class="btns-text">列表</div>
                            </div>
                            <div class="btns" @click="switchList('order')" v-else>
                                <a-icon class="btns-icon" type="container" />
                                <div class="btns-text">单据</div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="newProcess">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增</div>
                            </div>
                        </a-col>
                        <a-col :class="editMask?'btns-disable':''" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask?'':submit()">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col :class="editMask&&voucherState != 1?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask&&voucherState != 1?editClick():''">
                                <a-icon class="btns-icon" type="edit" />
                                <div class="btns-text">修改</div>
                            </div>
                        </a-col>
                        <a-col :class="orderId?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId?removeData():''">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">删除</div>
                            </div>
                        </a-col>
                        <a-col :class="orderId&&voucherState == 0?'':'btns-disable'" v-if="permissions.includes('InventoryWork:review')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId&&voucherState == 0?firstClick(1):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">复核</div>
                            </div>
                        </a-col>
                        <a-col :class="orderId&&voucherState == 1?'':'btns-disable'" v-if="permissions.includes('InventoryWork:review')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId&&voucherState == 1?firstClick(0):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">取消复核</div>
                            </div>
                        </a-col>
                        <a-col :class="orderId&&voucherState == 1?'':'btns-disable'" v-if="permissions.includes('InventoryWork:panel')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId&&voucherState == 1?auditClick(2):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">监盘</div>
                            </div>
                        </a-col>
                        <a-col :class="orderId&&voucherState == 2?'':'btns-disable'" v-if="permissions.includes('InventoryWork:panel')" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="orderId&&voucherState == 2?auditClick(1,'no'):''">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">取消监盘</div>
                            </div>
                        </a-col>
                        <a-col class="btn-item" :class="editMask==false?'':'btns-disable'" :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="editMask==false?syncOrder():''">
                                <a-icon class="btns-icon" type="undo" />
                                <div class="btns-text">撤销</div>
                            </div>
                        </a-col>
                        <!-- <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="searchDynamic">
                                <a-icon class="btns-icon" type="audit" />
                                <div class="btns-text">提取物料</div>
                            </div>
                        </a-col> -->
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">

                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="getList(3)">
                                <a-icon class="btns-icon" type="vertical-right" />
                                <div class="btns-text">首张</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="getList(1)">
                                <a-icon class="btns-icon" type="left" />
                                <div class="btns-text">上张</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="getList(2)">
                                <a-icon class="btns-icon" type="right" />
                                <div class="btns-text">下张</div>
                            </div>
                        </a-col>

                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div style="position:relative" class="btns" @click="getList(4)">
                                <a-icon class="btns-icon" type="vertical-left" />
                                <div class="btns-text">末张</div>
                                <div style="position:absolute;width:2px;height:36px;border-radius:6px;background:#ccc;top:0px;right:0px;"></div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="syncOrder">
                                <a-icon class="btns-icon" type="file-sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div ref="print" class="credentials-bom-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    <span class="text-name">{{voucherTitle}}</span><br>
                </h3>
                <a-row>
                    <a-col :span="24">
                        <section v-show="showModel=='order'">
                            <div>
                                <span class="audit-status" style="z-index:78" v-show="voucherState==1">已复核</span>
                                <span class="audit-status" style="z-index:78" v-show="voucherState==2">已监盘</span>
                                <span class="audit-status" style="z-index:78" v-show="voucherState==3">已批准</span>
                            </div>
                            <a-form-model :layout="formLayout">
                                <div class="header-box" style="position:relative">
                                    <!-- 遮罩（点击修改关闭遮罩） -->
                                    <div class="edit-mask-route" v-show="editMask"></div>
                                    <a-row class="order-dynamic-form-wrapper">
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="盘点方式" :rules="[{ required: true,tigger:'input' }]">
                                                <a-select v-model="dataJson.checkWay">
                                                    <a-select-option value="1" label="">
                                                        全盘
                                                    </a-select-option>
                                                    <a-select-option value="2" label="">
                                                        抽盘
                                                    </a-select-option>
                                                </a-select>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="仓库" :rules="[{ required: true,tigger:'input' }]">
                                                <a-input v-model="dataJson.warehouseName" @click="searchGroup('warehouseRef')" :style="styleOffice"></a-input>
                                                <searchGroupHeader ref="warehouseRef" :inputValue="dataJson.warehouseName" :componentName="'warehouse'" @clickItem="searchBackData"></searchGroupHeader>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="盘点日期" :rules="[{ required: true,tigger:'input' }]">
                                                <a-date-picker v-model="dataJson.voucherDate" @change="onChangeDate" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="盘点单编号">
                                                <a-input v-model="dataJson.voucherCode" disabled></a-input>
                                            </a-form-model-item>
                                        </a-col>

                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="帐面日期">
                                                <a-date-picker v-model="dataJson.voucherDate" :defaultValue="moment()" @change="onChangeDate" />
                                            </a-form-model-item>
                                        </a-col> -->
                                        <!-- <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="盘点会计期间">
                                                <a-input v-model="dataJson.unitName"></a-input>
                                            </a-form-model-item>
                                        </a-col> -->
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="部门">
                                                <a-input v-model="dataJson.officeName" @click="searchGroup('officeRef')" :style="styleProcess"></a-input>
                                                <searchGroupHeader ref="officeRef" :inputValue="dataJson.officeName" :componentName="'office'" @clickItem="searchBackData"></searchGroupHeader>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="盘点人">
                                                <a-input disabled v-model="dataJson.createUserName"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="监盘人">
                                                <a-input disabled v-model="dataJson.superviseUserName"></a-input>
                                                <!-- <searchGroupHeader ref="handlerJainRef" :inputValue="dataJson.handleUserName" :componentName="'employees'" @clickItem="searchBackData"></searchGroupHeader> -->
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="备注">
                                                <a-input v-model="dataJson.remarks"></a-input>
                                            </a-form-model-item>
                                        </a-col>

                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="状态">
                                                {{voucherState==0?'未复核':voucherState==1?'已复核':voucherState==2?'已监盘':voucherState==3?'已批准':''}}
                                            </a-form-model-item>
                                        </a-col>
                                    </a-row>
                                </div>
                                <div class="table-box">
                                    <!--修改状态的表格-->
                                    <a-table id="editBom_tb" v-if="!editMask" class="atable-edit" :columns="columns" :customRow="customClick" :data-source="dataSource" :pagination="false" bordered :scroll="{x:1000,y:300}">
                                        <template v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index">
                                            <div>
                                                <editable-cell v-if="isRouterAlive" :record="record" :checkType="checkType" :col="item" :text="text" @change="onCellChange(index, item, $event)" @choiceAddData="choiceAddData(index,col,$event)" @detailAddInventory="searchDynamic(index)" />
                                            </div>
                                        </template>
                                    </a-table>
                                    <!--查看状态的表格-->
                                    <a-table id="lookBom_tb" class="look-table" v-if="editMask" indentSize="18" :columns="columns" :data-source="innerData" :pagination="false" bordered :scroll="{x:1000,y:300}" @expand="expandChange" :loading="tableLoading">
                                        <!--发料方式-->
                                        <template slot="deliveryMethod" slot-scope="text">
                                            <div>{{ text == 1?'直接领料':text == 2?'调拨领料':text==3?'直接倒冲':text==4?'调拨倒冲':text==5?'不发料':'' }}</div>
                                        </template>
                                        <!--供应类型-->
                                        <template slot="supplyType" slot-scope="text">
                                            <div>{{ text == 1?'采购':text == 2?'自制':text==3?'委外':'' }}</div>
                                        </template>
                                    </a-table>
                                </div>
                                <div class="footer-box">
                                    <a-row class="order-dynamic-form-wrapper">
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="创建人">
                                                <a-input v-model="dataJson.createUserName" :disabled="true" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                            <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="创建时间">
                                                <a-input v-model="dataJson.createDate" :disabled="true" />
                                            </a-form-model-item>
                                        </a-col>
                                    </a-row>
                                </div>
                            </a-form-model>
                            <!-- <div class="mask-archives" v-show="maskArchives" @click="closeArchives"></div> -->
                        </section>
                        <section v-show="showModel == 'list'">
                            <a-row>
                                <a-col :span="4">
                                    <a-input-search class="search-btn" v-model="searchText" placeholder="盘点单编号" ref="searchInput" @search="searchList('list')" enter-button></a-input-search>
                                </a-col>
                            </a-row>
                            <a-row :gutter="[0,16]">
                                <a-col :span="24">
                                    <a-table style="min-height:300px;" id="dynamicList_tb" class="search-table-list" :columns="listCloums" :scroll="{x:500,y:500}" :data-source="listData" :customRow="customListClick" :rowClassName="rowClassName" bordered :pagination="pagination">

                                    </a-table>
                                </a-col>
                            </a-row>
                        </section>
                    </a-col>
                </a-row>

            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!--  <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--查询弹窗-->
        <search-wrapper-not-plan ref="searchWrapperRef" @searchPlan="setInventory" :type="'pancun'">
            <template slot="searchConditions">
                <!-- <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">仓库：</label>
                        <div class="filter-control">
                            <div style="background:rgba(0,0,0,0);width:100%;height:28px;z-index:2;position:absolute;top:10px;left:0;" @click="handleSearch('warehouseNameRef')"></div>
                            <a-input-search placeholder="请选择仓库" v-model="warehouseName" size="small" @search="handleSearch('warehouseNameRef')" />

                            <form-search-group ref="warehouseNameRef" :dynamicData="{name:'仓库',val:'warehouse',code:'warehouseId',value:warehouseName}" @clickItem="setValue"></form-search-group>
                        </div>
                    </div>
                </a-col> -->
                <!-- <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料分类：</label>
                        <div class="filter-control" ref="inventoryTypeWarpper" id="inventoryTypeId">
                            <a-input size="small" read-only onfocus="this.select()" :style="{'position':'relative','z-index':zIndexType}" v-model="searchData.inventoryTypeNameArray" @pressEnter="handleEnter(2)" @change="handleNameChange()" @click="handlInputArchives(4,'inventoryTypeWarpper')" />
                            <search-archives-type v-if="maskArchivesType" ref="searchArchivesRefType" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></search-archives-type>
                            <div class="mask-archives-type" v-show="maskArchivesType" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col> -->
                <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料 :</label>
                        <div class="filter-control" ref="inventoryCodeWarpper" id="inventoryCodeId">
                            <a-input-group size="small">
                                <a-row :gutter="8">
                                    <a-col :span="11">
                                        <a-input style="position:relative;z-index:3" size="small" v-model="searchData.inventoryCodeStart" onkeyup="value=value.replace(/[^\d]/g,'')" @pressEnter="handleEnter(1)" @change="handleArchiveChange()" @click="handlInputArchives(1,'inventoryCodeWarpper')" />
                                    </a-col>
                                    <a-col :span="2" class="text-center">至</a-col>
                                    <a-col :span="11">
                                        <a-input style="position:relative;z-index:3" size="small" v-model="searchData.inventoryCodeEnd" onkeyup="value=value.replace(/[^\d]/g,'')" @pressEnter="handleEnter(1)" @change="handleArchiveChange()" @click="handlInputArchives(2,'inventoryCodeWarpper')" />
                                    </a-col>
                                </a-row>
                            </a-input-group>
                            <searchArchives v-if="maskArchives" ref="searchArchivesRef" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></searchArchives>
                            <div class="mask-archives" v-show="maskArchives" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col>
                <a-col :span="6">
                    <div class="filter">
                        <label class="filter-label">ABC分类：</label>
                        <div class="filter-control">
                            <a-select style="width:100%;" v-model="searchData.abcClass" @change="checkArchives">
                                <a-select-option :value="0">
                                    全部
                                </a-select-option>
                                <a-select-option value="A">
                                    A
                                </a-select-option>
                                <a-select-option value="B">
                                    B
                                </a-select-option>
                                <a-select-option value="C">
                                    C
                                </a-select-option>
                            </a-select>
                        </div>
                    </div>
                </a-col>
                <a-col :span="6">
                    <div class="filter">
                        <label class="filter-label"></label>
                        <div class="filter-control">
                            <a-checkbox v-model="searchData.isInventoryQuantity" @change="searchDynamic">
                                库存量 > 0
                            </a-checkbox>
                        </div>
                    </div>
                </a-col>
                <!-- <a-col :span="12">
                    <div class="filter">
                        <label class="filter-label">物料名称：</label>
                        <div class="filter-control" ref="inventoryNameWarpper" id="inventoryNameId">
                            <a-input size="small" :style="{'position':'relative','z-index':zIndex}" v-model="inventoryName" @pressEnter="handleEnter(2)" @change="handleNameChange()" @click="handlInputArchives(3,'inventoryNameWarpper')" />
                            <searchArchivesName v-if="maskArchivesName" ref="searchArchivesRefName" :inventoryDomTop="inventoryDomTop" :inputType="inputType" :inputVal="inputVal" @closeArchives="closeArchives" @check="checkArchives"></searchArchivesName>
                            <div class="mask-archives-name" v-show="maskArchivesName" @click="handlCloseArchives"></div>
                        </div>
                    </div>
                </a-col> -->
                <a-col :span="24" style="margin-top:10px;">
                    <a-table :columns="inventoryColumns" :data-source="inventoryDataSource" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :pagination="paginationInventory" bordered :scroll="{x:800,y:320}">

                    </a-table>
                </a-col>
            </template>
        </search-wrapper-not-plan>

    </div>
</template>
<script>

import editableCell from "@/views/production/workshop/editTable/EditableCell"


import { getCodeApi, saveApi, deleteApi, pageApi, firstExamineApi, secondExamineApi, listSearchApi, getInventory, thirdExamineApi } from "@/api/inventory/inventoryWork";
import moment from "moment";
import { mapState } from "vuex";
import { searchWrapperNotPlan } from '@/components/SearchWrapper/';
import searchArchivesName from '@/components/OrderDynamicForm/searchArchivesName'
import searchArchivesType from '@/components/OrderDynamicForm/searchArchivesType'

import searchArchives from '@/components/OrderDynamicForm/searchArchives';
import { Controlwidth } from "@/utils/antTableComponents";

import searchGroupDetail from "@/components/PopUpLayer/searchGroupDetail";  //静态表格明细搜索组
import searchGroupHeader from "@/components/PopUpLayer/searchGroupHeader";
import getDate from "@/utils/tool/date";
import { numberFormat } from "@/utils/tool/number-formart";

export default {
    components: {
        editableCell,
        searchArchives,
        searchGroupDetail,
        searchGroupHeader,
        searchWrapperNotPlan,
        searchArchivesName,
        searchArchivesType,
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    data () {
        return {
            //----------↓样式----------
            fromStyle: { paddingTop: "8px" },
            labelCol: { span: 10 },
            wrapperCol: { span: 14 },
            editFalse: {
                borderBottom: '1px solid #ded7d7'
            },
            grid: {
                xs: 24,
                sm: 12,
                md: 8,
                lg: 6,
                xl: 6,
                xxl: 4
            },
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------
            showModel: 'order',
            // checkType: 3,//物料类型 1:采购 2:销售 3:生产（bom）
            editMask: false,
            dataSource: [],
            innerData: [],
            isRouterAlive: true,
            dragStartObj: null,     //拖动的目标
            dragEndObj: null,       //目标位置
            dragStartIndex: null,
            dragEndIndex: null,
            customClick: (record, index) => {
                return {
                    on: {
                        contextmenu: (e) => {//右键事件
                            e.preventDefault();
                            if (index <= this.dataSource.length) {
                                this.openMenu(e);
                                console.log('右键点击的', index);
                                this.thisClickId = index;
                                // this.thisClickRecord = record;
                            }
                        },

                    }
                }
            },
            customListClick: (record, index) => {
                return {
                    on: {
                        dblclick: (event) => {
                            event.preventDefault();
                            this.mouseIndex = record.key;
                            this.showModel = 'order';

                            this.orderId = record.id;
                            this.getList(5);
                        }
                    }
                }
            },
            mouseIndex: null,
            currentTableIndex: null,//鼠标左键点击的行
            orderId: null,
            nowRecord: {},
            voucherState: null,
            paginationInventory: {
                size: "small",
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.paginationInventory.pageSize}
                                min={1}
                                max={10}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSizeInventory(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.paginationInventory.current = page;
                    this.paginationInventory.pageSize = pageSize;
                    this.searchDynamic(this.currentTableIndex);
                },
            },
            pagination: {
                size: "small",
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={10}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.searchList('list');
                },
            },
            columns: [
                {
                    title: '序号',
                    customRender: (text, record, index) => {
                        return index + 1
                    },
                    align: 'center',
                    width: 40,
                },
                {
                    title: '物料编码',
                    dataIndex: 'inventoryCode',
                    width: 160,
                    scopedSlots: { customRender: 'inventoryCode' },
                    ellipsis: true,
                }, {
                    title: '物料名称',
                    dataIndex: 'inventoryName',
                    width: 100,
                    scopedSlots: { customRender: 'inventoryName' },
                    ellipsis: true,
                }, {
                    title: '规格型号',
                    dataIndex: 'inventorySpecification',
                    width: 100,
                    ellipsis: true,
                }, {
                    title: '主计量',
                    dataIndex: 'baseUnitName',
                    width: 100,
                    scopedSlots: { customRender: 'baseUnitName' },
                    align: 'left',
                    ellipsis: true,
                }, {
                    title: '货位',
                    dataIndex: 'inventoryLocationName',
                    width: 100,
                    scopedSlots: { customRender: 'inventoryLocationName' },
                    align: 'left',
                    ellipsis: true,
                }, {
                    title: '账面数量',
                    dataIndex: 'baseQuantity',
                    width: 100,
                    align: 'right',
                    ellipsis: true,
                }, {
                    title: '单价',
                    dataIndex: 'price',
                    width: 100,
                    align: 'right',
                    ellipsis: true,
                }, {
                    title: '账面金额',
                    dataIndex: 'lossOrGainAmount',
                    width: 100,
                    align: 'right',
                    ellipsis: true,
                    customRender: (text) => {
                        return numberFormat(text);
                    }
                }, {
                    title: <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> 盘点数量</div>,
                    dataIndex: 'checkQuantity',
                    width: 100,
                    scopedSlots: { customRender: 'checkQuantity' },
                    align: 'right',
                    ellipsis: true,
                }, {
                    title: '盘点金额',
                    dataIndex: 'checkAmount',
                    width: 100,
                    align: 'right',
                    scopedSlots: { customRender: 'checkAmount' },
                    ellipsis: true,
                }, {
                    title: '盈亏数量',
                    dataIndex: 'lossOrGainQuantity',
                    width: 100,
                    align: 'right',
                    ellipsis: true,
                    customRender: (text) => {
                        return numberFormat(text);
                    }
                }, {
                    title: '合理损耗率(%)',
                    dataIndex: 'reasonableLossRate',
                    width: 100,
                    scopedSlots: { customRender: 'reasonableLossRate' },
                    ellipsis: true,
                }, {
                    title: '盈亏比例(%)',
                    dataIndex: 'lossOrGainRate',
                    width: 140,
                    scopedSlots: { customRender: 'lossOrGainRate' },
                    ellipsis: true,
                }, {
                    title: '原因',
                    dataIndex: 'reason',
                    width: 140,
                    scopedSlots: { customRender: 'reason' },
                    ellipsis: true,
                }],
            visible: false,
            top: 0,
            left: 0,
            editColumnArraya: [],
            dataSourceNumber: 9,//默认渲染多少行表格数据
            dataJson: {
                checkWay: '',//盘点方式
                warehouseName: null,//仓库
                warehouseId: null,
                warehouseCode: null,//仓库编码
                createDate: null,//制单日期
                handleUserId: null,//盘点人ID
                handleUserName: null,//盘点人姓名
                officeId: null,//部门ID
                officeName: null,//部门名称
                orderDetailList: [],//明细
                remarks: null,//备注
                voucherCode: null,//单据编码
                voucherDate: null,//单据日期
                voucherState: null,//单据状态
                createUserName: null,//修改人
                createDate: null,//修改时间
            },
            searchData: {
                abcClass: 0,
                warehouseId: null,
                inventoryCodeStart: null,
                inventoryCodeEnd: null,
                inventoryTypeNameArray: [],
                inventoryTypeIdArray: [],
                isInventoryQuantity: false,//现存量是否大于0
            },
            inventoryDataSource: [],//搜索物料列表
            //物料
            maskArchives: false,
            maskArchivesName: false,
            maskArchivesType: false,
            inventoryDomTop: null,
            inventoryDomRight: null,
            inputVal: null,
            selectedRowKeys: [],
            selectedData: [],
            childrenData: [],//子级数据
            recordId: null,//当前点击展开的id
            styleProcess: {},
            styleOffice: {},
            position: {},
            tableLoading: false,//数据加载中

            searchInventoryCode: null,//母件编码搜索
            inventoryColumns: [{
                title: '仓库',
                dataIndex: 'actualWarehouseName',
                customRender: (text, record, index) => {
                    if(record.dataType == 2)return "";
                    if(!text)return "";
                    if(!record.warehouseCode)record.warehouseCode = "";
                    return text + "(" + record.warehouseCode +")";
                }
            }, 
            {
                title: '货位',
                dataIndex: 'inventoryLocationName',
                   customRender: (text, record, index) => {
                    if(record.dataType == 2)return "";
                    if(!text)return "";
                    if(!record.inventoryLocationCode)record.inventoryLocationCode = "";
                    return text + "(" + record.inventoryLocationCode +")";
                }
            },
            {
                title: '物料编码',
                dataIndex: 'inventoryCode',
            }, {
                title: '物料名称',
                dataIndex: 'inventoryName',
            }, {
                title: '规格型号',
                dataIndex: 'inventorySpecification',
            }, {
                title: '营销机构',
                dataIndex: 'agenciesName',
            }, {
                title: '可用量',
                dataIndex: 'availableQuantity',
            }, {
                title: '库存量',
                dataIndex: 'inventoryQuantity',
                customRender: (text) => {
                    return text || 0;
                }
            }, {
                title: '品牌',
                dataIndex: 'inBrand',
            }],
            inputType: null,
            listCloums: [{
                title: '仓库',
                dataIndex: 'warehouseName',
            }, {
                title: '盘点方式',
                dataIndex: 'checkWay',
                customRender: (text) => {
                    return text == 1 ? '全盘' : '抽盘';
                }
            }, {
                title: '盘点日期',
                dataIndex: 'voucherDate',
            }, {
                title: '盘点单编号',
                dataIndex: 'voucherCode',
            }, {
                title: '部门',
                dataIndex: 'officeName',
            }, {
                title: '盘点人',
                dataIndex: 'createUserName',
            }, {
                title: '监盘人',
                dataIndex: 'superviseUserName',
            }, {
                title: '状态',
                dataIndex: 'voucherState',
                customRender: (text) => {
                    return text == 0 ? '未复核' : text == 1 ? '已复核' : text == 2 ? '已监盘' : text == 3 ? '已批准' : '';
                }
            }, {
                title: '备注',
                dataIndex: 'remark',
            }],
            listData: [],//列表数据
            searchText: null,
        };
    },
    created () {
        this.tableInit();//初始化表格
        this.editColumnArray(this.columns);
        this.getList(4);//获取最新一条数据
    },
    updated () {
        Controlwidth("route_tb", 50);
        Controlwidth("editBom_tb", 80);
        Controlwidth("lookBom_tb", 80);
    },
    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
    },
    methods: {
        moment,
        tableInit () {
            for (let i = 0; i < this.dataSourceNumber; i++) {
                this.dataSource.push({})
            }
            this.reload();
            console.log(this.dataSource)
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        newProcess () {
            //新增（初始化数据）
            this.showModel = 'order';
            this.dataSource = [];
            this.mouseIndex = null;
            this.editMask = false;
            this.tableInit();
            this.dataJson = {
                checkWay: '',//盘点方式
                voucherDate: getDate.getCurrentMoment().format('YYYY-MM-DD'),//默认当前时间
            };
            this.orderId = null;
            this.voucherState = 0;
            this.searchData.warehouseId = null;
            this.getCode();
        },
        openMenu (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu () {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd () {
            //新增数据
            const { count, dataSource } = this;
            const newData = {};
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length, 0, newData);
            })
            console.log('新增行：', this.dataSource)
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            console.log(numberId);
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [..._this.dataSource];
                    console.log(_this.dataSource.length);
                    if (dataSource.length - 1 > _this.dataSourceNumber) {
                        //大于规定行数(删除)
                        _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = ""
                                    }
                                }
                            }
                        }
                        _this.dataSource = dataSource;
                    }


                    _this.reload();
                },
                onCancel () { },
            });
        },
        getCode () {
            //获取单据编码
            getCodeApi().then(res => {
                if (res.code === 200) {
                    this.dataJson.voucherCode = res.message;
                    this.$forceUpdate()
                }
            })
        },
        onChangeDate (v, s) {
            this.dataJson.voucherDate = s;
        },
        onCellChange (indexTable, dataIndex, value) {
            const dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);

            this.$set(target, dataIndex, value)
            if (dataIndex == 'inventoryLocationName') {
                //货位名称
                if (value) {
                    target['inventoryLocationName'] = value.name;
                    target['inventoryLocationCode'] = value.code;
                    target['inventoryLocationId'] = value.id;
                }
            } else if (dataIndex == 'checkQuantity') {
                //计算盘点金额
                if (value) {
                    target['checkQuantity'] = value;
                    target['checkAmount'] = (target['checkQuantity'] * target['price']).toFixed(2);
                    //盈亏数量（账面数量-盘点数量）
                    target['lossOrGainQuantity'] = Number(target['checkQuantity']) - Number(target['baseQuantity']);
                }
            }

            this.$nextTick(() => {
                this.dataSource = dataSource;
                this.reload();
            })
        },

        //获取可编辑的列名
        editColumnArray (column) {
            let editcloumn = [];
            column.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumnArraya = editcloumn;
        },
        getList (type) {
            this.editMask = true;
            this.tableLoading = true;
            //翻页
            let postData = {
                actionType: type,
                currentId: this.orderId,
                isLossOrGain: false,//是否是盈亏表
            }
            pageApi(postData).then(response => {
                if (response.code === 200) {
                    this.tableLoading = false;
                    if (response.data == null) {
                        if (type == 1 || type == 3) {
                            this.$message.warning('已经是首页了');
                            return;
                        } else if (type == 2) {
                            this.$message.warning('已经是尾页了');
                            return;
                        } else if (type == 4) {
                            //新建
                            this.newProcess();
                        }
                    } else {
                        const { orderDetailList } = response.data;

                        orderDetailList.forEach(item => {
                            item.key = item.id;
                        });
                        this.dataJson = response.data;
                        this.orderId = response.data.id;
                        this.voucherState = response.data.voucherState;//状态
                        this.dataJson.orderDetailList = orderDetailList;
                        this.dataSource = orderDetailList;
                        this.innerData = orderDetailList;

                        this.searchData.warehouseId = response.data.warehouseId;

                        this.$forceUpdate();
                    }

                }
            }).catch(error => {
                this.tableLoading = false;
            });
        },
        //保存
        submit () {
            console.log(this.dataSource);

            if (!this.dataJson.checkWay) {
                this.$message.warning('请选择盘点方式');
                return;
            }
            for (let i = 0; i < this.dataSource.length; i++) {
                for (let j = 0; j < this.dataSource.length; j++) {
                    if (this.dataSource[i].inventoryId == this.dataSource[j].inventoryId && i != j &&this.dataSource[i].inventoryLocationId==this.dataSource[j].inventoryLocationId&& this.dataSource[i].inventoryId && this.dataSource[j].inventoryId) {
                        this.$message.warning(`第${i + 1}行物料和第${j + 1}行物料不能相同！`)
                        return;
                    }
                }
            }
            this.dataJson.orderDetailList = this.dataSource.filter(item => { return item.inventoryId });

            this.dataJson.createDate = null;

            // let reg = /^[0-9][0-9]*(\.[0-9]{1,2})?$/;
            // if (!reg.test(this.dataJson.finishProductRate) || this.dataJson.finishProductRate < 0 || this.dataJson.finishProductRate > 100) {
            //     this.$message.warning('成品率必须大于0小于100的整数或者两位小数')
            //     return;
            // }
            if (JSON.stringify(this.dataJson.orderDetailList) == '[]') {
                this.$message.warning('明细不能为空')
                return;
            }
            let detais = this.dataJson.orderDetailList;
            for (let i = 0; i < detais.length; i++) {
                detais[i].warehouseCode = this.dataJson.warehouseCode;
                detais[i].warehouseId = this.dataJson.warehouseId;
                detais[i].warehouseName = this.dataJson.warehouseName;
                if (!detais[i].checkQuantity) {
                    this.$message.warning('盘点数量必须填写！')
                    return;
                }
            }
            let requestData = this.dataJson;
            saveApi(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.getList(4);
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => {
                // this.isSaveRun = true;
            })
        },
        removeData () {
            //删除
            // if (this.selectedRowKeys.length != 1) {
            //     this.$message.warning('请选择一条数据');
            //     return;
            // }

            let _this = this;
            this.$confirm({
                title: <span>您确定要{<span style="color:red;">删除</span>}该条单据吗？</span>,
                content: "",
                onOk () {
                    deleteApi({ id: _this.orderId }).then(response => {
                        if (response.code === 200) {
                            _this.$message.success('删除成功');
                            _this.orderId = null;
                            _this.searchData.warehouseId = null;
                            _this.getList(4);
                        } else {
                            _this.$message.error(response.message);
                        }
                    }).catch((e) => {
                    })
                },
                onCancel () { }
            });
        },
        handlInputArchives (type, ref) {
            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'none';

            this.inputType = type;
            if (type == 1 || type == 2) {
                this.maskArchives = true;
                this.zIndex = 1;
                this.zIndexType = 1;
            } else if (type == 3) {
                this.zIndex = 5;
                this.zIndexType = 1;
                this.maskArchivesName = true;
            } else if (type == 4) {
                this.zIndexType = 6;
                this.zIndex = 1;
                this.maskArchivesType = true;
            }
            //获取位置
            console.log(this.$refs[`${ref}`].parentNode.offsetTop);
            let loc = this.$refs[`${ref}`].getBoundingClientRect();
            this.inventoryDomTop = Math.abs(loc.top);


        },
        closeArchives () {
            this.maskArchives = false;
        },
       // 弹窗查询搜索
        checkArchives (data) {
            this.maskArchives = false;
            this.maskArchivesName = false;
            //返回值处理
            const { dataSource } = this;
            if (data[1] == 1) {
                //起始值
                this.searchData.inventoryCodeStart = data[0][0].inventoryCode;
            }
            if (data[1] == 2) {
                //起始值
                this.searchData.inventoryCodeEnd = data[0][0].inventoryCode;
            }
            if (data[1] == 3) {
                //物料编码名称
                this.searchData.inventoryName = data[0][0].inventoryName;
            }
            if (data[1] == 4) {
                //物料分类
                console.log(data[0]);
                let tData = data[0].checkedNodes;
                let typeNameArray = [];
                let typeIdArray = [];
                tData.forEach(item => {
                    typeNameArray.push(item.data.class);
                    typeIdArray.push(item.data.props.id);
                });

                this.searchData.inventoryTypeNameArray = typeNameArray.join(';')
                this.searchData.inventoryTypeIdArray = typeIdArray;
            }
            this.closeArchives();
            //搜索盘存数据
            this.searchData.abcClass == 0 ? this.searchData.abcClass = null : '';
            this.searchData.current = this.paginationInventory.current;
            this.searchData.size = this.paginationInventory.pageSize;
            getInventory(this.searchData).then(res => {
                if (res.code === 200) {
                    this.inventoryDataSource = res.data.records;

                    this.paginationInventory.total = res.data.total;
                    this.paginationInventory.pageSize = res.data.size;
                    this.paginationInventory.current = res.data.current;

                }
            })
        },

        // checkArchivesDDDDDDDDD (data) {
        //     this.maskArchives = false;
        //     console.log(data);
        //     //返回值处理
        //     this.dataJson.inventoryId = data[0][0].id;
        //     this.dataJson.inventoryCode = data[0][0].inventoryCode;
        //     this.dataJson.inventoryName = data[0][0].inventoryName;
        //     this.dataJson.inventorySpecification = data[0][0].inventorySpecification;
        //     this.dataJson.baseUnit = data[0][0].unitId ? data[0][0].unitId : data[0][0].unitGroupId;
        //     this.dataJson.baseUnitName = data[0][0].unitName ? data[0][0].unitName : data[0][0].unitGroupName;
        // },
        rowClassName (record, index) {
            return this.mouseIndex == record.key ? 'hoverRowStyl' : '';
        },
        handleArchiveChange (t) {
            //物料编码搜索
            if (t == 1) {
                this.inputVal = this.dataJson.inventoryCode;
            } else if (t == 2) {
                this.inputVal = this.dataJson.inventoryName;
            }
            this.$refs.searchArchivesRef.inputVal = this.inputVal;
            this.$refs.searchArchivesRef.getData(1);
        },
        onSelectChange (keys, data) {
            this.selectedRowKeys = keys;
            this.selectedData = data;
            console.log(keys, data)
        },
        getDetails (dd) {
            let record = JSON.parse(JSON.stringify(dd));
            this.editMask = true;
            let requestData = {
                bomId: record.id
            }
            details(requestData).then(response => {
                if (response.code === 200) {

                    //修改表格的处理
                    let newDataJson = this.listData.filter(item => item.id == record.id);
                    console.log(this.listData, record, newDataJson);
                    this.dataJson = JSON.parse(JSON.stringify(newDataJson[0]));;

                    this.dataSource = JSON.parse(JSON.stringify(response.data));

                    if (this.dataSource.length < this.dataSourceNumber) {
                        for (let i = 0; i < this.dataSourceNumber - response.data.length; i++) {
                            this.dataSource.push({})
                        }
                    }

                    //查看表格的处理
                    let backData = response.data;
                    for (let i = 0; i < backData.length; i++) {
                        if (backData[i].bomId != null) {
                            backData[i].children = [];
                        }
                        backData[i].key = backData[i].id;
                    }
                    this.innerData = backData;

                    this.reload();
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        editClick () {
            this.editMask = false;
            const length = this.dataSource.length;
            if (length < this.dataSourceNumber) {
                for (let i = 0; i < this.dataSourceNumber - length; i++) {
                    this.dataSource.push({})
                }
            }
            this.reload();
        },
        auditClick (type, yn) {
            //审核
            let requestData = {
                id: this.orderId,
                status: type
            }
            secondExamineApi(requestData).then((response) => {
                if (response.code === 200) {
                    if (type == 2) {
                        this.$message.success('监盘成功');
                        this.getList(4);
                        this.voucherState = 2;
                    }
                    if (type == 1) {
                        if (yn) {
                            this.$message.success('取消监盘成功');
                        } else {
                            this.$message.success('复核成功');
                        }
                        this.getList(4);
                        this.voucherState = 1;
                    }
                    if (type == 0) {
                        this.$message.success('取消复核成功');
                        this.getList(4);
                        this.voucherState = 0;
                    }

                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        firstClick (type) {
            //复核
            let requestData = {
                id: this.orderId,
                status: type
            }
            firstExamineApi(requestData).then((response) => {
                if (response.code === 200) {
                    if (type == 1) {
                        this.$message.success('复核成功');
                        this.getList(4);
                        this.voucherState = 1;
                    }
                    if (type == 0) {
                        this.$message.success('取消复核成功');
                        this.getList(4);
                        this.voucherState = 0;
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        expandChange (expanded, record) {
            if (record.children.length > 0) return false;
            //table展开
            details({ "bomId": record.bomId }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    data.forEach(item => {
                        if (item.bomId) {
                            item.children = [];
                        }
                        item.key = item.id;
                    });

                    // this.childrenData = data;//子集数据
                    // this.recordId = record.bomId;//当前点击展开的bomId
                    record.children = data;
                    // this.nextArray(this.innerData);
                } else {
                    this.$message.error(response.message);
                }
            }).catch((e) => { })
        },
        nextArray (array) {
            for (const i in array) {
                let data = array[i];
                if (data.children) {
                    if (data.bomId == this.recordId) {
                        data.children = this.childrenData;
                    }
                    this.nextArray(data.children);
                }
            }
        },
        searchGroup (ref) {
            //搜索组件的显示
            this.$nextTick(() => {
                this.$refs[`${ref}`].showModal();
            })


        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }

            this.pagination.current = 1;
            this.pagination.pageSize = size;
            this.searchList('list');
        },
        changePageSizeInventory(e){
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            this.paginationInventory.current = 1;
            this.paginationInventory.pageSize = size;
            this.searchDynamic(this.currentTableIndex);
        },
        searchBackData (record) {
            if (record.codesName == "warehouse") {
                console.log(this.searchData.warehouseId);
                if (this.searchData.warehouseId != null) {
                    let _this = this;
                    this.$confirm({
                        title: "确认",
                        content: "仓库发生变化，将清空明细数据，是否继续？",
                        onOk () {
                            _this.dataSource = [];
                            for (let i = 0; i < _this.dataSourceNumber; i++) {
                                _this.dataSource.push({})
                            }

                            _this.reload();

                            _this.$set(_this.dataJson, 'warehouseName', record.whName)
                            _this.$set(_this.dataJson, 'warehouseId', record.id);
                            _this.$set(_this.searchData, 'warehouseId', record.id);
                            _this.$store.commit('SET_WHEREHOUSEID', record.id)
                        },
                        onCancel () { },
                    });
                } else {
                    this.$set(this.dataJson, 'warehouseName', record.whName)
                    this.$set(this.dataJson, 'warehouseId', record.id);
                    this.$set(this.searchData, 'warehouseId', record.id);
                    this.$store.commit('SET_WHEREHOUSEID', record.id)
                }
            } else if (record.codesName == 'office') {
                this.$set(this.dataJson, 'officeName', record.officeName)
                this.$set(this.dataJson, 'officeId', record.id)
            } else if (record.codesName == 'employees') {
                this.$set(this.dataJson, 'handleUserName', record.name)
                this.$set(this.dataJson, 'handleUserId', record.id)
            }
        },
        setInventory () {
            //关闭搜索弹窗，植入物料
            console.log(this.selectedData);

            if (this.selectedData.length > 0) {
                this.choiceAddData(this.currentTableIndex, this.selectedData)
                this.$refs.searchWrapperRef.cancel();//关闭弹窗
                this.selectedRowKeys = [];
                this.selectedData = [];
            } else {
                this.$message.warning('请至少选择一条数据');
                return;
            }
        },
        choiceAddData (index, record) {
            //物料多选
            let newData = [...record];
            console.log("bbq选择物料档案", newData, this.dataSource)
            for (let i = 0; i < newData.length; i++) {
                let newDetails = {};
                newDetails['inventoryCode'] = newData[i].inventoryCode;//物料编码
                newDetails['inventoryId'] = newData[i].id;//物料名称
                newDetails['inventoryName'] = newData[i].inventoryName;//物料名称
                newDetails['inventorySpecification'] = newData[i].inventorySpecification;//规格型号
                newDetails['inventoryLocationId'] = newData[i].inventoryLocationId;
                newDetails['inventoryLocationName'] = newData[i].inventoryLocationName;
                newDetails['inventoryLocationCode'] = newData[i].inventoryLocationCode;
                if (newData[i].unitType == '多计量') {
                    newDetails['baseUnit'] = newData[i].mainUnit;
                    newDetails['baseUnitName'] = newData[i].mainUnitName;
                    newDetails['unitGroupId'] = newData[i].unitGroupId;

                } else {
                    newDetails['unitId'] = newData[i].unitId;//
                    newDetails['baseUnit'] = newData[i].unitId;//
                    newDetails['baseUnitName'] = newData[i].unitName;//
                }
                newDetails['price'] = newData[i].latestCost ? newData[i].latestCost : newData[i].referenceCost ? newData[i].referenceCost : '';//单价（最新成本or参考成本）
                newDetails['baseQuantity'] = newData[i].inventoryQuantity || 0;//账面数量
                newDetails['reasonableLossRate'] = newData[i].lossRate;//合理损耗率

                newDetails['lossOrGainAmount'] = (newData[i].inventoryQuantity * newDetails['price']).toFixed(2);//账面金额
                console.log("选择的物料信息：", newDetails);
                if (newData.length == 1) {
                    this.dataSource.splice(index + i, 1, newDetails);
                } else {
                    this.dataSource.splice(index + i, 0, newDetails);
                }
            }
            this.reload();
        },
        handleSearch (key, confirm, col) {
            //table搜索
            confirm();
            console.log(key, confirm, col)
            this.searchInventoryCode = key[0];

            let searchText = { 'searchKey': this.searchInventoryCode }
            this.getList(searchText)
        },
        handleReset (clearFilters) {
            clearFilters();
            this.searchInventoryCode = '';
            this.getList()
        },
        syncOrder () {
            //刷新
            this.getList(4);
        },
        switchList (type) {
            this.showModel = type;
        },
        searchList (type) {
            this.showModel = type;
            //列表搜索
            const { searchArray } = this;
            let data = {
                current: this.pagination.current,
                size: this.pagination.pageSize,
                isLossOrGain: false,
                voucherCode: this.searchText,
            }
            listSearchApi(data).then((response) => {
                if (response.code === 200) {
                    let backdData = response.data.records;
                    console.log('--------搜索返回值：', backdData);
                    backdData.forEach(item => {
                        item.key = item.id;
                    });
                    this.listData = backdData;

                    this.pagination.current = response.data.current;
                    this.pagination.pageSize = response.data.size;
                    this.pagination.total = response.data.total;

                    // this.mouseIndex = null;
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //点击新增 的物料编码 选择物料框
        searchDynamic (index) {
            this.currentTableIndex = index;
            if (!this.dataJson.warehouseId) {
                this.$message.warning('请先选择仓库！')
                return;
            } else {
                //搜索盘存数据
                this.searchData.abcClass == 0 ? this.searchData.abcClass = null : '';
                this.searchData.current = this.paginationInventory.current;
                this.searchData.size = this.paginationInventory.pageSize;
                getInventory(this.searchData).then(res => {
                    if (res.code === 200) {
                        this.inventoryDataSource = res.data.records;
                        this.paginationInventory.total = res.data.total;
                        this.paginationInventory.pageSize = res.data.size;
                        this.paginationInventory.current = res.data.current;
                    }
                })
                this.$refs.searchWrapperRef.showModel();
            }
        },
        //关闭物料档案弹窗
        handlCloseArchives () {
            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'translate(0px, 0px)';

            if (this.inputType == 1 || this.inputType == 2) {
                this.maskArchives = false;
                this.$refs.searchArchivesRef.closeModel();
            } else if (this.inputType == 3) {
                this.maskArchivesName = false;
                this.$refs.searchArchivesRefName.closeModel();
            } else if (this.inputType == 4) {
                this.maskArchivesType = false;
                this.$refs.searchArchivesRefType.closeModel();
            }
        },
        handleEnter (t) {
            if (t == 1) {
                this.$refs.searchArchivesRef.handleEnter();
            } else {
                this.$refs.searchArchivesRefName.handleEnter();
            }
        },
        handleNameChange () {
            //物料名称搜索
            this.$refs.searchArchivesRefName.inputVal = this.inventoryName;
            this.$refs.searchArchivesRefName.getData(1);
        },
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .credentials-bom-wrapper {
        padding: 12px 0;
        height: auto;
        overflow-y: auto;
        font-size: 14px;
        .ant-form-item {
            margin: 0;
        }
        .mask-archives {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            // background: rgba(220, 53, 69, 0.5);
            background: rgba(0, 0, 0, 0);
            z-index: 2;
        }
        .ant-table-tbody > tr > td {
            cursor: pointer;
        }
        .hoverRowStyl {
            background-color: rgba(24, 144, 255, 0.2);
            td {
                color: #222;
            }
        }
        .ant-table colgroup > col.ant-table-selection-col {
            width: 30px;
        }
        .edit-mask-route {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 800;
            background: rgba(255, 255, 255, 0.1);
        }
        .inner-table {
            margin: 0 !important;
        }

        .look-table {
            .ant-table-body {
                min-height: 300px;
            }
        }

        .order-dynamic-form-wrapper {
            label:not(.form-check-label):not(.custom-file-label) {
                font-weight: normal;
            }
            .ant-form-item-label {
                line-height: 32px;
                height: 32px;
            }

            .ant-form-item-control {
                line-height: 30px;
            }
            .ant-input {
                height: 28px;
            }

            .ant-input[disabled] {
                background: #f9f9f9;
            }
        }

        .atable-edit {
            .ant-table-tbody > tr > td {
                padding: 0px !important;
            }
        }

        .drag-line-top td {
            border-top: 1px dashed #1890ff;
        }

        .drag-line-bottom td {
            border-bottom: 1px dashed #1890ff !important;
        }
        .position-zindex-1 {
            position: relative;
            z-index: 71;
        }

        .ant-select-selection--single {
            height: 28px;
        }
    }
    .tabbl-bom {
        .ant-table-scroll {
            height: 450px !important;
        }
        .ant-table-wrapper .ant-table-pagination {
            text-align: right !important;
        }
    }
</style>